import { stringify } from 'querystring';
import router from 'umi/router';
import { fakeAccountLogin, getFakeCaptcha, userLogin } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: { // 详情参考：https://github.com/dvajs/dva-knowledgemap#effects
    *login({ payload }, { call, put }) {  // *function() 是一个内部使用了yield迭代器的函数
      console.log("===>>> payload", payload, payload.userName, typeof (payload.userName))
      // call()：用于调用异步逻辑
      // const response = yield call(fakeAccountLogin, payload);
      // console.log("===>>> response", response)
      const _payload = {
        username: payload.userName,
        password: payload.password,
        recaptcha: null
      }
      const _response = yield call(userLogin, _payload)
      // console.log("===>>> _response", _response)
      if ("string" == typeof (_response)){  // 若认证通过，返回字符串类型的token

        const response = {
          token: _response,
          user: payload.userName,
        };

        // localStorage.clear()  // 清空localStorage
        yield put({  // put()：用于触发action
          type: 'changeLoginStatus',
          payload: response,
        }); // Login successfully
        // console.log("===>>> localStorage", localStorage, localStorage.getItem('authority'))

        // 验证通过的跳转
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;

        if (redirect) {
          const redirectUrlParams = new URL(redirect);

          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);

            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }

        router.replace(redirect || '/');
        
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    logout() {
      const { redirect } = getPageQuery(); // Note: There may be security issues, please note

      if (window.location.pathname !== '/user/login' && !redirect) {
        router.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
      
      localStorage.removeItem("authority");
      localStorage.removeItem("token");
      console.log("===>> logout", localStorage)
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload);  // 将认证信息存到localStorage中 | currentAuthority：用户名
      return { ...state, status: payload.status, type: payload.type };
    },
  },
};
export default Model;
